from PIL import Image, ImageDraw, ImageFont
from paddleocr import PaddleOCR

ocr = PaddleOCR(use_gpu=True, lang='ch')
image_path = '/home/songzhijun/图片/2.jpg'
res = ocr.ocr(image_path, cls=True)
print(res)


def draw_ocr_boxes(image_path, boxes, texts):
    img = Image.open(image_path)
    img = Image.new('RGB', img.size, (255, 255, 255))

    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype("./chinese_cht.ttf", size=15)

    # 遍历每个文本框和对应的文本
    for box, text in zip(boxes, texts):
        draw.rectangle(box, outline='red', width=2)
        x, y = box[:2]
        draw.text((x, y), text, font=font, fill='black')

    img.save('/home/songzhijun/图片/image_with_boxes_and_text.jpg')


# 示例文本框坐标和对应的文字
boxes = [(*i[0][0], *i[0][2]) for i in res[0]]
texts = [i[1][0] for i in res[0]]
draw_ocr_boxes('/home/songzhijun/图片/2.jpg', boxes, texts)